require([
    'require',
    'chart'
], function (require) {
    require(['chart', 'ionic'], function (echarts) {
            angular.module('myApp', ['ionic'])
                .config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
                    $stateProvider
                        .state('states', {
                            url: '/states',
                            templateUrl: 'templates/states.html',
                            controller: 'StatesCtrl'
                        })
                        .state('clients', {
                            url: '/clients',
                            templateUrl: 'templates/clients.html',
                            controller: 'ClientsCtrl'
                        })
                        .state('styles', {
                            url: '/styles/:clientId',
                            templateUrl: 'templates/styles.html',
                            controller: 'StylesCtrl'
                        })
                        .state('clientdetail', {
                            url: '/clients/:clientId',
                            templateUrl: 'templates/client_detail.html',
                            controller: 'ClientDetailCtrl'
                        })
                        .state('messagedetail', {
                            url: '/messages/:messageId',
                            templateUrl: 'templates/message_detail.html',
                            controller: 'MessageDetailCtrl'
                        })
                        .state('pushmessagedetail', {
                            url: '/pushmessages/:messageId',
                            templateUrl: 'templates/push_message_detail.html',
                            controller: 'PushMessageDetailCtrl'
                        });
                    $urlRouterProvider.otherwise('/states');

                    $ionicConfigProvider.platform.android.navBar.alignTitle('center');
                    $ionicConfigProvider.platform.android.backButton.previousTitleText(false);
                    $ionicConfigProvider.platform.android.navBar.transition('view');
                    $ionicConfigProvider.platform.android.views.transition('ios');
                    $ionicConfigProvider.platform.android.views.swipeBackEnabled(true);
                    $ionicConfigProvider.platform.android.views.swipeBackHitWidth(45);
                    $ionicConfigProvider.platform.android.tabs.style('standard');
                    $ionicConfigProvider.platform.android.tabs.position('bottom');
                    $ionicConfigProvider.platform.android.form.toggle('large');

                    $ionicConfigProvider.platform.default.backButton.previousTitleText(false);
                    $ionicConfigProvider.platform.default.backButton.text(false);
                })
                .run(function () {
                    u9.hideLoading();
                })
                .directive('shareCombobox', ['$document', function ($document) {
                    return {
                        restrict: 'E',
                        scope: true,
                        replace: true,
                        link: function ($scope, $element) {

                            var keyUp = function (e) {
                                if (e.which == 27) {
                                    $scope.cancel();
                                    $scope.$apply();
                                }
                            };

                            var backdropClick = function (e) {
                                if (e.target == $element[0]) {
                                    $scope.cancel();
                                    $scope.$apply();
                                }
                            };
                            $scope.$on('$destroy', function () {
                                $element.remove();
                                $document.unbind('keyup', keyUp);
                            });

                            $document.bind('keyup', keyUp);
                            $element.bind('click', backdropClick);
                        },
                        template: '<div class="action-sheet-backdrop">' +
                        '<div class="action-sheet-wrapper share-sheet">' +
                        '<div class="combobox-sheet">' +
                        '<div class="combobox-body">' +
                        '<ion-scroll class="combobox-content" scrollbar-y="false">' +
                        '<div>' +
                        '<div class="divShare"><img class="sharePng" src="img/icon_friendscircle.png" style="width:20%; height:20%;text-align: center;" ng-click="buttonClicked(1)" /></div>' +

                        '<div class="divShare"><img class="sharePng" src="img/icon_wechat.png" style="width:20%; height:20%;text-align: center;" ng-click="buttonClicked(0)"/></div>' +

                        '</div>' +
                        '</ion-scroll>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '</div>'
                    };
                }])
                .directive("ngTouchmove", function () {
                    return {
                        controller: function ($scope, $element) {
                            $element.bind('touchstart', onTouchStart);
                            var startPosition, endPosition, deltaX;

                            function onTouchStart($event) {
                                var touch = $event.touches[0];
                                startPosition = {
                                    x: touch.pageX,
                                    y: touch.pageY
                                }
                                event.preventDefault();
                                if (touch.pageX == $event.changedTouches[0].pageX) {
                                    endPosition = {
                                        x: touch.pageX,
                                        y: touch.pageY
                                    }
                                }
                                $element.bind('touchmove', onTouchMove);
                                $element.bind('touchend', onTouchEnd);

                            };

                            function onTouchMove($event) {
                                var touch = $event.touches[0];
                                endPosition = {
                                    x: touch.pageX,
                                    y: touch.pageY
                                }
                            };

                            function onTouchEnd($event) {
                                deltaX = endPosition.x - startPosition.x;
                                //$scope.$parent.someFunction(deltaX);
                                event.preventDefault();
                                $element.unbind('touchmove', onTouchMove);
                                $element.unbind('touchend', onTouchEnd);
                            };
                        }
                    };
                })
                .directive('myDirective', function() {
                    return {
                        restrict: 'A',
                        replace: true,
                        scope: {
                            myUrl: '=someAttr', // 经过了修改
                            myLinkText: '@'
                        },
                        template: '\
                        <div>\
                            <label>My Url Field:</label>\
                            <input type="text"\
                                ng-model="myUrl" />\
                            <a href="{{myUrl}}">{{myLinkText}}</a>\
                        </div>'
                    }})
                .directive('chatScroll', ['$timeout', '$ionicScrollDelegate', function ($timeout, $ionicScrollDelegate) {
                    return {
                        restrict: 'E',
                        scope: {
                            quickCambers: '=',
                            activeCamber: '='
                        },
                        transclude: true,
                        replace: true,
                        template: '<div class="chat-scroll">' +
                        '<ion-scroll scrollbar-y="false" has-bouncing="true" on-scroll="onScroll()">' +
                        '<div class="chat-scroll-wrapper" ng-transclude></div>' +
                        '</ion-scroll>' +
                        '<div class="quick-bar">' +
                        '<div class="quick-item" ng-repeat="quickCamber in quickCambers" ' +
                        'ng-class="{active:quickCamber===activeCamber}" ng-click="setActiveCamber(quickCamber)">' +
                        '{{quickCamber}}' +
                        '</div>' +
                        '</div>' +
                        '</div>',
                        compile: function (element, attr) {
                            var ionScroll = element.find('ion-scroll');

                            angular.forEach({
                                'delegate-handle': attr.delegateHandle
                            }, function (value, name) {
                                if (angular.isDefined(value)) {
                                    ionScroll.attr(name, value);
                                }
                            });

                            return {pre: prelink};

                            function prelink($scope, $element, $attr) {
                                var autoScrolling = false;
                                $scope.setActiveCamber = function (camber) {
                                    $scope.activeCamber = camber;

                                    var chats = $element[0].querySelector('.chat-scroll-wrapper').children,
                                        len = chats.length,
                                        temp = 0;
                                    if (len === 0) {
                                        return;
                                    }
                                    for (var i = 0; i < len; i++) {
                                        if (chats[i].innerText === camber) {
                                            break;
                                        }
                                    }
                                    if (i === len) {
                                        return;
                                    }
                                    var scrollCtrl = $ionicScrollDelegate.$getByHandle($attr.delegateHandle);
                                    autoScrolling = true;
                                    scrollCtrl.scrollTo(0, chats[i].offsetTop, true);
                                    $timeout(function () {
                                        autoScrolling = false;
                                    }, 300);
                                };
                                $scope.onScroll = function () {
                                    if (autoScrolling) {
                                        return;
                                    }
                                    var scrollCtrl = $ionicScrollDelegate.$getByHandle($attr.delegateHandle),
                                        pos = scrollCtrl.getScrollPosition(),
                                        scrollView = scrollCtrl.getScrollView();
                                    if (pos.top < 0 || pos.top > scrollView.__maxScrollTop) {
                                        return;
                                    }
                                    var chats = $element[0].querySelector('.chat-scroll-wrapper').children,
                                        len = chats.length,
                                        temp = 0;
                                    if (len === 0) {
                                        return;
                                    }
                                    for (var i = 0; i < len; i++) {
                                        if (chats[i].offsetTop > parseInt(pos.top)) {
                                            temp = i - 1;
                                            break;
                                        }
                                    }
                                    if (i === 0) {
                                        temp = 0;
                                    } else if (i === len) {
                                        temp = len - 1;
                                    }
                                    var camber = chats[temp].innerText;
                                    if (camber !== $scope.activeCamber) {
                                        $scope.$apply(function () {
                                            $scope.activeCamber = camber;
                                        });
                                    }
                                };
                            }
                        }
                    };
                }])
                .factory('shareCombobox', [
                    '$rootScope',
                    '$document',
                    '$compile',
                    '$animate',
                    '$timeout',
                    '$ionicTemplateLoader',
                    '$ionicPlatform',
                    function ($rootScope, $document, $compile, $animate, $timeout, $ionicTemplateLoader, $ionicPlatform) {

                        return {
                            show: actionSheet
                        };

                        function actionSheet(opts) {
                            var scope = $rootScope.$new(true);

                            angular.extend(scope, {
                                cancel: angular.noop,
                                data: [],
                                displayField: 'name',
                                valueField: 'id',
                                buttonClicked: angular.noop,
                                $deregisterBackButton: angular.noop,
                                cancelOnStateChange: true
                            }, opts || {});

                            // Compile the template
                            var element = scope.element = $compile('<share-combobox ng-class="cssClass"></share-combobox>')(scope);

                            // Grab the sheet element for animation
                            var sheetEl = angular.element(element[0].querySelector('.action-sheet-wrapper'));

                            var stateChangeListenDone = scope.cancelOnStateChange ?
                                $rootScope.$on('$stateChangeSuccess', function () {
                                    scope.cancel();
                                }) :
                                angular.noop;

                            // removes the actionSheet from the screen
                            scope.removeSheet = function (done) {
                                if (scope.removed) return;

                                scope.removed = true;
                                sheetEl.removeClass('action-sheet-up');
                                $document[0].body.classList.remove('action-sheet-open');
                                scope.$deregisterBackButton();
                                stateChangeListenDone();

                                $animate.removeClass(element, 'active').then(function () {
                                    scope.$destroy();
                                    element.remove();
                                    // scope.cancel.$scope is defined near the bottom
                                    scope.cancel.$scope = sheetEl = null;
                                    (done || angular.noop)();
                                });
                            };

                            scope.showSheet = function (done) {
                                if (scope.removed) return;

                                $document[0].body.appendChild(element[0]);
                                $document[0].body.classList.add('action-sheet-open');

                                $animate.addClass(element, 'active').then(function () {
                                    if (scope.removed) return;
                                    (done || angular.noop)();
                                });
                                $timeout(function () {
                                    if (scope.removed) return;
                                    sheetEl.addClass('action-sheet-up');
                                }, 20, false);
                            };

                            // registerBackButtonAction returns a callback to deregister the action
                            scope.$deregisterBackButton = $ionicPlatform.registerBackButtonAction(
                                scope.cancel,
                                300
                            );

                            scope.cancel = function () {
                                scope.removeSheet(opts.cancel);
                            };

                            scope.buttonClicked = function (index) {
                                if (opts.buttonClicked(index) === true) {
                                    scope.removeSheet();
                                }
                            };

                            scope.showSheet();
                            scope.cancel.$scope = scope;

                            return scope.cancel;
                        }
                    }])
                .factory('Clients', function ($q) {
                    var Data = {
                        //所有客户
                        clients: [],
                        //选中的客户
                        selectedClients: [],
                        //选中列表
                        selectedList: [],
                        //首次运行
                        first: 1,
                        //首次运行
                        first_list: 1,
                        UserCode: u9.getLoginData().UserCode + '',
                        //删除用户
                        deleteClients: []
                        //消息
                    };

                    function all() {
                        return Data.clients;
                    }

                    //获取单个所有客户的新消息数
                    function getOneClientsMsgCount(i, Code) {
                        var deferred = $q.defer();
                        u9.callSV({
                            name: 'UFIDA.U9.ISV.MessageRemindSV.IGetUnReadTargetMessageCountSV',
                            params: [false, "SysCustomerInfo", Code],
                            onSuccess: function (data) {
                                Data.selectedClients[i].newMsg = data
                                deferred.resolve(data);
                            },
                            onFailure: function (err) {
                                console.log(err);
                                deferred.reject(err);
                            }
                        });
                        //Data.selectedClients[i].newMsg = 8;
                        //deferred.resolve(8);
                        return deferred.promise;
                    }

                    //获取所有客户的新消息数
                    function getClientsMsgCount(selectClients) {
                        var deferred = $q.defer();
                        u9.showLoading();
                        var promises = [];
                        var clientCode;
                        for (var i in  selectClients) {
                            clientCode = selectClients[i].Code;
                            promises.push(getOneClientsMsgCount(i, clientCode));
                        }
                        $q.all(promises).then(function () {
                            //u9.alert("获取消息数成功");
                            deferred.resolve(Data.selectedClients);
                        }, function (error) {
                            u9.alert("获取消息数失败");
                            deferred.resolve(Data.selectedClients);
                            deferred.reject(error);
                        })['finally'](function () {
                            u9.hideLoading();
                        });
                        return deferred.promise;
                    }
                    function getSelectedClients(){
                        return Data.selectedClients;
                    }

                    function allSelectedClients() {
                        var deferred = $q.defer();
                        //首次执行取本地
                        if (Data.first == 1) {
                            console.log("first");
                            Data.selectedClients = angular.fromJson(localStorage.getItem("selectedClients"));
                            Data.first++;
                        }
                        deferred.resolve(Data.selectedClients);
                        return deferred.promise;
                    }

                    function allSelected() {
                        //首次执行取本地
                        if (Data.first_list == 1) {
                            console.log("first_list");
                            Data.selectedList = angular.fromJson(localStorage.getItem("selecteds"));
                            Data.first_list++;
                        }
                        return Data.selectedList;
                    }

                    function getClient(clientId) {
                        for (var i = 0; i < Data.selectedClients.length; i++) {
                            if (Data.selectedClients[i].id === parseInt(clientId)) {
                                return Data.selectedClients[i];
                            }
                        }
                        return null;
                    }

                    function addSelectedClients(selecteds) {
                        var deferred = $q.defer();
                        Data.deleteClients = [];
                        window.localStorage.removeItem("selecteds");
                        window.localStorage.removeItem("selectedClients");
                        Data.selectedList = selecteds;
                        if (Data.selectedClients == null) {
                            Data.selectedClients = [];
                        }
                        if (Data.selectedClients.length == 0) {
                            for (var i in selecteds) {
                                for (var j in Data.clients) {
                                    if (selecteds[i] == Data.clients[j].id) {
                                        Data.selectedClients.push(Data.clients[j]);
                                        break;
                                    }
                                }
                            }
                        }
                        else {
                            //为选中客户列表添加新元素
                            var a = 0;
                            for (var i in selecteds) {
                                a = 0;
                                for (var j in Data.selectedClients) {
                                    if (selecteds[i] != Data.selectedClients[j].id) {
                                        a++;
                                    }
                                }
                                if (a == Data.selectedClients.length) {
                                    for (var h in Data.clients) {
                                        if (selecteds[i] == Data.clients[h].id) {
                                            //var dd  = Data.clients[h].style.set(Styles.all());
                                            //Data.selectedClients.push(dd);
                                            Data.selectedClients.push(Data.clients[h]);
                                            break;
                                        }
                                    }
                                }
                            }
                            //为选中客户列表删除元素，记录删除元素的index
                            var p = 0;
                            for (var m in Data.selectedClients) {
                                p = 0;
                                for (var n in selecteds) {
                                    if (Data.selectedClients[m].id != selecteds[n]) {
                                        p++;
                                    }
                                }
                                if (p == selecteds.length) {
                                    Data.deleteClients.push(Data.selectedClients[m]);
                                    Data.selectedClients.splice(m, 1);
                                }
                            }
                        }
                        window.localStorage.setItem("selecteds", angular.toJson(selecteds));
                        window.localStorage.setItem("selectedClients", angular.toJson(Data.selectedClients));
                        deferred.resolve(Data.deleteClients);
                        return deferred.promise;
                    }
                    //首页删除用户，同时删除订阅
                    function deleteClientStyle(id){
                        for (var j in Data.selectedClients) {
                            if (id == Data.selectedClients[j].id) {
                                Data.selectedClients.splice(j,1);
                                break;
                            }
                        }
                        for (var i in Data.selectedList) {
                            if (id == Data.selectedList[i]) {
                                Data.selectedList.splice(i,1);
                                break;
                            }
                        }
                        window.localStorage.setItem("selecteds", angular.toJson(Data.selectedList));
                        window.localStorage.setItem("selectedClients", angular.toJson(Data.selectedClients));


                    }
                    function getClientsDatas() {
                        var deferred = $q.defer();
                        var contacts = [];
                        u9.showLoading();
                        u9.callSV({
                            name: 'UFIDA.U9.ISV.MFGRestMessageSV.Message.IGetCustomerListByUser',
                            params: [Data.UserCode],
                            onSuccess: function (data) {
                                u9.hideLoading();
                                Data.clients = [];
                                ////引入 makepy.js
                                //new_element = document.createElement("script");
                                //new_element.setAttribute("type", "text/javascript");
                                //new_element.setAttribute("src", " makepy.js");
                                //document.body.appendChild(new_element);
                                var letters = [];
                                var currentCharCode = 'A'.charCodeAt(0) - 1;
                                var temp;
                                var Name;
                                var Code;
                                var ID;
                                var pinyin
                                for (var i in data) {
                                    temp = data[i];
                                    Name = temp.Name;
                                    Code = temp.Code;
                                    ID = temp.ID;
                                    pinyin = makePy(Name)[0];
                                    Data.clients.push({
                                        Code: Code, id: ID, name: Name, pinyin: pinyin, newMsg: 0, style: []
                                    });
                                }
                                Data.clients
                                    .sort(function (a, b) {
                                        return a.pinyin > b.pinyin ? 1 : -1;
                                    })
                                    .forEach(function (person) {
                                        var pinyin = person.pinyin;
                                        var personCharCode = pinyin.toUpperCase().charCodeAt(0);
                                        var difference = personCharCode - currentCharCode;
                                        var isHas = false;//设置没有内容的字母索引不显示
                                        for (var i = 1; i <= difference; i++) {
                                            if (i == difference) {
                                                isHas = true;
                                            }
                                            else {
                                                isHas = false;
                                            }
                                            addLetter(currentCharCode + i, isHas);
                                        }
                                        currentCharCode = personCharCode;
                                        contacts.push(person);
                                    });
                                //If names ended before Z, add everything up to Z
                                for (var i = currentCharCode + 1; i <= 'Z'.charCodeAt(0); i++) {
                                    addLetter(i, false);
                                }
                                function addLetter(code, isHas) {
                                    var letter = String.fromCharCode(code);
                                    contacts.push({
                                        isLetter: isHas,
                                        letter: letter
                                    });
                                    letters.push(letter);
                                }

                                deferred.resolve(contacts);
                            },
                            onFailure: function (err) {
                                u9.hideLoading();
                                console.log(err);
                                deferred.reject(err);
                            }
                        });
                        return deferred.promise;
                    }

                    return {
                        all: all,
                        getOneClientsMsgCount: getOneClientsMsgCount,
                        getClientsMsgCount: getClientsMsgCount,
                        allSelectedClients: allSelectedClients,
                        getSelectedClients:getSelectedClients,
                        allSelected: allSelected,
                        getClient: getClient,
                        addSelectedClients: addSelectedClients,
                        getClientsDatas: getClientsDatas,
                        deleteClientStyle:deleteClientStyle

                    }
                })

                .factory('Messages', function ($q) {
                    // Might use a resource here that returns a JSON array
                    var num = 0;
                    var num2 = 0;
                    var newMessages = [{
                        id: 100,
                        read: false,
                        name: '新的通知0',
                        detail: '新的订单(单号：po201500000000),已出货',
                        time: '2015/9/6 21:00:16'

                    }, {
                        id: 101,
                        read: false,
                        name: '新的通知1',
                        detail: '新的订单(单号：po201500000000),已出货',
                        time: '2015/9/6 21:00:16'

                    }, {
                        id: 102,
                        read: false,
                        name: '新的通知2',
                        detail: '新的订单(单号：po201500000000),已出货',
                        time: '2015/9/6 21:00:16'

                    }, {
                        id: 103,
                        read: false,
                        name: '新的通知3',
                        detail: '新的订单(单号：po201500000000),已出货',
                        time: '2015/9/6 21:00:16'

                    }, {
                        id: 104,
                        read: false,
                        name: '新的通知4',
                        detail: '新的订单(单号：po201500000000),已出货',
                        time: '2015/9/6 21:00:16'

                    }, {
                        id: 105,
                        read: false,
                        name: '新的通知5',
                        detail: '新的订单(单号：po201500000000),已出货',
                        time: '2015/9/6 21:00:16'

                    }];
                    var loadMessages = [
                        {
                            id: 106,
                            read: true,
                            name: '更多通知0',
                            detail: '销售订单(单号：po201500000000),已出货',
                            time: '2015/9/6 21:00:16'

                        }, {
                            id: 107,
                            read: true,
                            name: '更多通知1',
                            detail: '销售订单(单号：po201500000000),已出货',
                            time: '2015/9/6 21:00:16'

                        }, {
                            id: 108,
                            read: true,
                            name: '更多通知2',
                            detail: '销售订单(单号：po201500000000),已出货',
                            time: '2015/9/6 21:00:16'

                        }, {
                            id: 109,
                            read: true,
                            name: '更多通知3',
                            detail: '销售订单(单号：po201500000000),已出货',
                            time: '2015/9/6 21:00:16'

                        }, {
                            id: 110,
                            read: true,
                            name: '更多通知4',
                            detail: '销售订单(单号：po201500000000),已出货',
                            time: '2015/9/6 21:00:16'

                        }, {
                            id: 111,
                            read: true,
                            name: '更多通知5',
                            detail: '销售订单(单号：po201500000000),已出货',
                            time: '2015/9/6 21:00:16'

                        }
                    ]
                    // Some fake testing data
                    var messages = [{
                        id: 0,
                        read: true,
                        name: '订单出货通知',
                        detail: '销售订单(单号：po201500000000),已出货',
                        time: '2014/9/6 21:00:16'

                    }, {
                        id: 1,
                        read: false,
                        name: '订单退货通知',
                        detail: '销售订单(单号：po201511111111),已出货',
                        time: '2015/9/6 21:00:16'

                    }, {
                        id: 2,
                        read: true,
                        name: '订单出货通知',
                        detail: '销售订单(单号：po201500000000),已出货',
                        time: '2013/9/6 21:00:16'

                    }, {
                        id: 3,
                        read: true,
                        name: '订单出货通知',
                        detail: '销售订单(单号：po201500000000),已出货',
                        time: '2015/8/6 21:00:16'

                    }, {
                        id: 4,
                        read: true,
                        name: '订单出货通知',
                        detail: '销售订单(单号：po201500000000),已出货',
                        time: '2015/9/6 21:00:16'

                    }, {
                        id: 5,
                        read: true,
                        name: '订单出货通知',
                        detail: '销售订单(单号：po201500000000),已出货',
                        time: '2015/9/16 21:00:16'

                    }];

                    return {
                        //通过messageId获取客户code
                        getClientCode: function (messageId) {
                            var deferred = $q.defer();
                            u9.showLoading();
                            u9.callSV({
                                name: '',
                                params: [messageId],
                                onSuccess: function (data) {
                                    u9.hideLoading();
                                    deferred.resolve();
                                },
                                onFailure: function (err) {
                                    u9.hideLoading();
                                    console.log(err);
                                    deferred.reject(err);
                                }
                            });
                            return deferred.promise;
                        },
                        all: function () {
                            return messages;
                        },
                        //获取未读消息数据
                        getUnreadData: function (Code,name) {
                            var deferred = $q.defer();
                            u9.showLoading();
                            u9.callSV({
                                name: 'UFIDA.U9.ISV.MessageRemindSV.IGetUnReadTargetMessageSV',
                                params: [false, "SysCustomerInfo", Code],
                                onSuccess: function (data) {
                                    u9.hideLoading();
                                    messages = [];
                                    if(data==null || data.length==0) {
                                        u9.alert("消息数据为空，此为假数据");
                                        messages.push({id: 5, read: false, name: '订单出货通知'
                                            , detail: '销售订单(单号：po201500000000),已出货'
                                            , time: '2015/9/16 21:00:16'
                                            , client: name});
                                    }else{
                                        var temp;
                                        var title;
                                        var content;
                                        var time;
                                        var id;
                                        for (var i in data) {
                                            temp = data[i];
                                            id = temp.ID;
                                            title = temp.Title;
                                            content = temp.Content.substring(temp.Content.indexOf("的")+1);
                                            time = temp.SendTime;
                                            messages.push({id: id, read: false, name: title, detail: content, time: time, client: name});
                                        }
                                    }
                                    deferred.resolve(messages);
                                },
                                onFailure: function (err) {
                                    u9.hideLoading();
                                    messages = [];
                                    u9.alert("获取消息数据失败，此为假数据");
                                    messages.push({id: 5, read: false, name: '订单出货通知'
                                        , detail: '销售订单(单号：po201500000000),已出货'
                                        , time: '2015/9/16 21:00:16'
                                        , client: name});
                                    deferred.resolve(messages);
                                    console.log(err);
                                    deferred.reject(err);
                                }
                            });
                            return deferred.promise;
                        },
                        //更新
                        getUpdateData: function () {
                            //var Display = 5;
                            if (num < newMessages.length) {
                                messages.unshift(newMessages[num]);
                                //messages = messages.slice(0,Display);
                                num++;
                            }
                            return messages;
                        },
                        //加载更多
                        loadMoreData: function () {
                            if (num2 < loadMessages.length) {
                                messages.push(loadMessages[num2]);
                                num2++;
                            }
                            return messages;
                        },
                        //设置未读消息为已读
                        setMsgRead: function (msgId) {
                            for (var i = 0; i < messages.length; i++) {
                                if (messages[i].id === parseInt(msgId)) {
                                    messages[i].read = true;
                                }
                            }
                        }
                    };
                })

                .factory('States', function ($q) {
                    var states = [{
                        id: 0,
                        name: 'xxxxxxxxxxxxx公司',
                        finance_msg: {
                            name: '财务信息',
                            detail: [{
                                name: '未出货金额',
                                value: '$6666666666669'
                            }, {
                                name: '未立账金额',
                                value: '$6666666666668'
                            }, {
                                name: '应收总额',
                                value: '$6666666666668'
                            }, {
                                name: '逾期款',
                                value: '$6666666666668'
                            }, {
                                name: '坏账款',
                                value: '$6666666666668'
                            }, {
                                name: '预收款',
                                value: '$6666666666668'
                            }, {
                                name: '累计退货款',
                                value: '$6666666666668'
                            }]
                        },
                        business_msg: {
                            name: '业务信息',
                            detail: [{
                                name: '最近订货日',
                                value: '2015-9-13'
                            }, {
                                name: '最近出货日',
                                value: '2015-9-13'
                            }, {
                                name: '最近开票日',
                                value: '2015-9-13'
                            }, {
                                name: '最近退货日',
                                value: '2015-9-13'
                            }, {
                                name: '最近收款日',
                                value: '2015-9-13'
                            }]
                        },
                        client_chart: {
                            name: '客户报表',
                            detail: []
                        }
                    }];
                    return {
                        //获取客户状态信息
                        getClientState: function (clientId) {
                            var deferred = $q.defer();
                            u9.showLoading();
                            u9.callSV({
                                name: 'UFIDA.U9.ISV.MFGRestMessageSV.Message.IGetCustomerAmount',
                                params: [clientId],
                                onSuccess: function (data) {
                                    for (var i in data) {
                                        if (i == "UnShipmentedAmount") {//未出货金额
                                            states[0].finance_msg.detail[0].value = data[i];
                                        }
                                        if (i == "UnConfirmAmount") {//未立账金额
                                            states[0].finance_msg.detail[1].value = data[i];
                                        }
                                        if (i == "ARBalance") {//应收总额
                                            states[0].finance_msg.detail[2].value = data[i];
                                        }
                                        if (i == "OverdueARAmount") {//逾期款
                                            states[0].finance_msg.detail[3].value = data[i];
                                        }
                                        if (i == "BadDebtsAmount") {//坏账款
                                            states[0].finance_msg.detail[4].value = data[i];
                                        }
                                        if (i == "PreGathering") {//预收款
                                            states[0].finance_msg.detail[5].value = data[i];
                                        }
                                        if (i == "TotalReturnAmount") {//累计退货款
                                            states[0].finance_msg.detail[6].value = data[i];
                                        }
                                        if (i == "LastSaleDate") {//最近订货日
                                            states[0].business_msg.detail[0].value = data[i].substring(0,data[i].indexOf(" "));
                                        }
                                        if (i == "LastShipmentDate") {//最近出货日
                                            states[0].business_msg.detail[1].value = data[i].substring(0,data[i].indexOf(" "));
                                        }
                                        if (i == "LastInvoiceDate") {//最近开票日
                                            states[0].business_msg.detail[2].value = data[i].substring(0,data[i].indexOf(" "));
                                        }
                                        if (i == "LastReturnDate") {//最近退货日
                                            states[0].business_msg.detail[3].value = data[i].substring(0,data[i].indexOf(" "));
                                        }
                                        if (i == "LastReceivementDate") {//最近收款日
                                            states[0].business_msg.detail[4].value = data[i].substring(0,data[i].indexOf(" "));
                                        }
                                    }
                                    u9.hideLoading();
                                    deferred.resolve(states);
                                },
                                onFailure: function (err) {
                                    u9.hideLoading();
                                    console.log(err);
                                    deferred.reject(err);
                                }
                            });
                            return deferred.promise;
                        },
                        //获取客户状态信息图表
                        getClientStateChart: function (clientId) {
                            var deferred = $q.defer();
                            u9.showLoading();
                            u9.callSV({
                                name: 'UFIDA.U9.ISV.MFGRestMessageSV.Message.IGetOrderMoneyOnYear',
                                params: [clientId],
                                onSuccess: function (data) {
                                    console.log(data)
                                    u9.hideLoading();
                                    deferred.resolve(data);
                                },
                                onFailure: function (err) {
                                    u9.hideLoading();
                                    console.log(err);
                                    deferred.reject(err);
                                }
                            });
                            return deferred.promise;
                        }
                    };
                })

                .factory('Styles', function (Clients, $q) {
                    var first_style = 1;
                    var styles = [];//所有标签状态数组
                    var UserCode = u9.getLoginData().UserCode + '';//用户编码
                    var CustomerCode = "";//客户编码
                    var Marks = [];//标签集合
                    var numsAdd = [];//存入新添加用户的index(查找新添加用户，只添加标签)
                    //var numsEdit = [];//存入旧用户的index(添加或删除标签)
                    var deleteIndexs = [];//所有用户要删除的标签Indexs
                    var addIndexs = [];//所有用户要添加的标签
                    var oneDeleteIndexs = [];//单个用户要删除的标签
                    var oneAddIndexs = [];//单个用户要添加的标签

                    //所有客户style的获取
                    function getAllStyle() {
                        var deferred = $q.defer();
                        //首次执行本地有数据取本地数据，否则取网络数据（因为需要记录标签选择）
                        if (first_style == 1) {
                            var styless = angular.fromJson(localStorage.getItem("styles"));
                            if (styless == null) {//网络获取
                                u9.showLoading();
                                u9.callSV({
                                    name: 'UFIDA.U9.ISV.MFGRestMessageSV.Message.IGetMark',
                                    params: [],
                                    onSuccess: function (data) {
                                        u9.hideLoading();
                                        var temp;
                                        var Name;
                                        var Code;
                                        var ID;
                                        for (var i in data) {
                                            temp = data[i];
                                            Name = temp.Name;
                                            Code = temp.Code;
                                            ID = temp.ID;
                                            styles.push({Code: Code, id: ID, name: Name, isselect: false});
                                        }
                                        deferred.resolve(styles);
                                    },
                                    onFailure: function (err) {
                                        u9.hideLoading();
                                        console.log(err);
                                        deferred.reject(err);
                                    }
                                });
                                window.localStorage.setItem("styles", angular.toJson(styles));
                                //styles = angular.fromJson(localStorage.getItem("styles"));
                            }
                            else {
                                styles = styless;
                                deferred.resolve(styles);
                            }
                            first_style++;
                        }
                        else {
                            deferred.resolve(styles);
                        }
                        return deferred.promise;
                    }

                    //单个客户style的获取
                    function clientStyle(clientId) {
                        var allSelectedClients = Clients.getSelectedClients();
                        for (var i in  allSelectedClients) {
                            if (allSelectedClients[i].id == parseInt(clientId)) {
                                var temp = allSelectedClients[i].style;
                            }
                        }
                        return temp;
                    }

                    //初始化，添加所有标签到每个客户
                    function addStyleToClient() {
                        var allSelectedClients = Clients.getSelectedClients();
                        //有选中客户数据，为客户添加标签数据
                        if (allSelectedClients != null) {
                            for (var i in allSelectedClients) {
                                if (allSelectedClients[i].style.length == 0) {
                                    allSelectedClients[i].style = angular.copy(styles);
                                    //allSelectedClients[i].style = styles;
                                    numsAdd.push(i);
                                }
                            }
                        }
                    }

                    //改变所有客户的标签选择
                    function changeAllStyleChecked(_index) {
                        var allSelectedClients = Clients.getSelectedClients();
                        for (var i in  allSelectedClients) {
                            var temp = allSelectedClients[i].style[_index]
                            temp.isselect = !temp.isselect;
                        }
                        if (styles[_index].isselect) {
                            deleteIndexs.push(_index);
                        }
                        else {
                            addIndexs.push(_index);
                        }
                        styles[_index].isselect = !styles[_index].isselect;
                        //存标签数据
                        window.localStorage.removeItem("styles");
                        window.localStorage.setItem("styles", angular.toJson(styles));
                        //存选中客户数据
                        window.localStorage.removeItem("selectedClients");
                        window.localStorage.setItem("selectedClients", angular.toJson(allSelectedClients));
                        return styles;
                    }

                    //改变单个客户标签选择
                    function changeStyleChecked(clientId, index) {
                        //var stylesV = angular.copy(styles);;
                        var j = 0;
                        var allSelectedClients = Clients.getSelectedClients();
                        for (var i in  allSelectedClients) {
                            if (allSelectedClients[i].id == parseInt(clientId)) {
                                j = i;
                                var temp = allSelectedClients[i].style[index]
                                if (temp.isselect) {
                                    oneDeleteIndexs.push(index);
                                }
                                else {
                                    oneAddIndexs.push(index);
                                }
                                temp.isselect = !temp.isselect;
                            }
                        }
                        //存选中客户数据
                        window.localStorage.removeItem("selectedClients");
                        window.localStorage.setItem("selectedClients", angular.toJson(allSelectedClients));
                        return allSelectedClients[j].style;
                    }

                    //访问增加标签的接口
                    function addStyle(UserCode, CustomerCode, Marks) {
                        var deferred = $q.defer();
                        var jsonData = {
                            name: 'UFIDA.U9.ISV.MFGRestMessageSV.Message.ISubscriberMessage',
                            params: [UserCode, CustomerCode, Marks],
                            onSuccess: function (data) {//返回true或false
                                //alert("addStyleReturnData-------" + data);
                                deferred.resolve(data);
                            },
                            onFailure: function (err) {
                                console.log(err);
                                deferred.reject(err);
                            }
                        };
                        u9.callSVAlone(jsonData);
                        return deferred.promise;
                    }

                    //访问删除标签的接口
                    function deleteStyle(UserCode, CustomerCode, Marks) {
                        var deferred = $q.defer();
                        var jsonData = {
                            name: 'UFIDA.U9.ISV.MFGRestMessageSV.Message.IUnSubscriberMessage',
                            params: [UserCode, CustomerCode, Marks],
                            onSuccess: function (data) {
                                //alert("deleteStyleReturnData-------" + data);
                                deferred.resolve(data);
                            },
                            onFailure: function (err) {
                                console.log(err);
                                deferred.reject(err);
                            }
                        };
                        u9.callSVAlone(jsonData);
                        return deferred.promise;
                    }

                    //单个用户取消标签订阅,订阅的标签都取消订阅（删除的客户）
                    function deleteOneClientStyles(deleteOne) {
                        var deferred = $q.defer();
                        u9.showLoading();
                        Marks = [];

                        var deleteStyles = [];
                        var style;

                            CustomerCode = deleteOne.Code;
                            deleteStyles = deleteOne.style;
                            for (var c in deleteStyles) {
                                style = deleteStyles[c];
                                if (style.isselect) {
                                    Marks.push(style.id);
                                }
                            }
                        deleteStyle(UserCode, CustomerCode, Marks).then(function (isSuccess) {
                            if (isSuccess) {
                                //u9.alert("取消标签订阅成功");
                            }
                            else {
                                //u9.alert("取消标签订阅失败");
                            }
                            u9.hideLoading();
                            deferred.resolve(isSuccess);
                        });
                        return deferred.promise;
                    }

                    //用户取消标签订阅,订阅的标签都取消订阅（删除的客户）
                    function deleteClientStyles(deletes) {
                        var deferred = $q.defer();
                        u9.showLoading();
                        Marks = [];
                        var promises = [];
                        var deleteStyles = [];
                        var style;
                        for (var j in  deletes) {
                            CustomerCode = deletes[j].Code;
                            deleteStyles = deletes[j].style;
                            for (var c in deleteStyles) {
                                style = deleteStyles[c];
                                if (style.isselect) {
                                    Marks.push(style.id);
                                }
                            }
                            promises.push(deleteStyle(UserCode, CustomerCode, Marks));
                        }
                        $q.all(promises).then(function () {
                            deferred.resolve(true);
                            //u9.alert("修改标签订阅成功");
                        }, function (error) {
                            deferred.reject(error);
                        })['finally'](function () {
                            u9.hideLoading();
                        });
                        return deferred.promise;
                    }

                    //上传新用户的消息标签和修改老用户的消息标签
                    function updateAllStyles() {
                        var deferred = $q.defer();
                        u9.showLoading();
                        var style;
                        Marks = [];
                        var Markss = [];
                        var allSelectedClients = Clients.getSelectedClients();
                        //没有改变标签选择，但是有新用户，要为新用户加入默认标签
                        if (addIndexs.length == 0 && deleteIndexs.length == 0) {
                            for (var c in styles) {
                                style = styles[c];
                                if (style.isselect) {
                                    Marks.push(style.id);
                                }
                            }
                            if (numsAdd.length != 0 && Marks.length != 0) {
                                var promises = [];
                                for (var a in numsAdd) {
                                    CustomerCode = allSelectedClients[numsAdd[a]].Code;
                                    promises.push(addStyle(UserCode, CustomerCode, Marks));
                                }
                                $q.all(promises).then(function () {
                                    //u9.alert("修改标签订阅成功");
                                    deferred.resolve(true);
                                }, function (error) {
                                    deferred.reject(error);
                                })['finally'](function () {
                                    u9.hideLoading();
                                });
                            }
                            else {
                                deferred.resolve(true);
                                u9.hideLoading();
                            }
                        }
                        //有改变标签选择
                        else {
                            //每个用户即增加标签，又删除标签
                            if (addIndexs.length != 0 && deleteIndexs.length != 0) {
                                var promises = [];
                                var promisess = [];
                                for (var i in addIndexs) {
                                    Marks.push(styles[addIndexs[i]].id);
                                }
                                for (var k in deleteIndexs) {
                                    Markss.push(styles[deleteIndexs[k]].id);
                                }
                                for (var j in  allSelectedClients) {
                                    CustomerCode = allSelectedClients[j].Code;
                                    promises.push(addStyle(UserCode, CustomerCode, Marks));
                                    promisess.push(deleteStyle(UserCode, CustomerCode, Markss));
                                }
                                $q.all(promises).then(function () {
                                    deferred.resolve(true);
                                    //u9.alert("全部客户添加标签成功");
                                    $q.all(promisess).then(function () {
                                        deferred.resolve(true);
                                        //u9.alert("全部客户删除标签成功");
                                        //u9.alert("修改标签订阅成功");
                                    }, function (error) {
                                        deferred.reject(error);
                                    })['finally'](function () {
                                        u9.hideLoading();
                                    });
                                }, function (error) {
                                    deferred.reject(error);
                                });
                            }
                            //每个用户增加标签
                            if (addIndexs.length != 0 && deleteIndexs.length == 0) {
                                var promises = [];
                                for (var i in addIndexs) {
                                    Marks.push(styles[addIndexs[i]].id);
                                }
                                for (var j in  allSelectedClients) {
                                    CustomerCode = allSelectedClients[j].Code;
                                    promises.push(addStyle(UserCode, CustomerCode, Marks));
                                }
                                $q.all(promises).then(function () {
                                    deferred.resolve(true);
                                    //u9.alert("修改标签订阅成功");
                                }, function (error) {
                                    deferred.reject(error);
                                })['finally'](function () {
                                    u9.hideLoading();
                                });
                            }
                            //每个用户删除标签
                            if (deleteIndexs.length != 0 && addIndexs.length == 0) {
                                var promises = [];
                                for (var i2 in deleteIndexs) {
                                    Marks.push(styles[deleteIndexs[i2]].id);
                                }
                                for (var j2 in  allSelectedClients) {
                                    CustomerCode = allSelectedClients[j2].Code;
                                    promises.push(deleteStyle(UserCode, CustomerCode, Marks));
                                }
                                $q.all(promises).then(function () {
                                    deferred.resolve(true);
                                    //u9.alert("修改标签订阅成功");
                                }, function (error) {
                                    deferred.reject(error);
                                })['finally'](function () {
                                    u9.hideLoading();
                                });
                            }
                        }
                        numsAdd = [];
                        addIndexs = [];
                        deleteIndexs = [];
                        return deferred.promise;
                    }

                    //上传单个用户的消息标签
                    function updateOneStyles(clientId) {
                        var deferred = $q.defer();
                        u9.showLoading();
                        CustomerCode = '';
                        Marks = [];
                        var Markss = [];
                        var oneStyles;
                        var allSelectedClients = Clients.getSelectedClients();
                        for (var a in  allSelectedClients) {
                            if (allSelectedClients[a].id == parseInt(clientId)) {
                                oneStyles = allSelectedClients[a].style;
                                CustomerCode = allSelectedClients[a].Code;
                            }
                        }
                        if (oneAddIndexs.length == 0 && oneDeleteIndexs.length == 0) {
                            deferred.resolve(true);
                            u9.hideLoading();
                        }
                        //有改变标签选择
                        else {
                            //每个用户即增加标签，又删除标签
                            if (oneAddIndexs.length != 0 && oneDeleteIndexs.length != 0) {
                                for (var j in oneAddIndexs) {
                                    Marks.push(oneStyles[oneAddIndexs[j]].id);
                                }
                                for (var j2 in oneDeleteIndexs) {
                                    Markss.push(oneStyles[oneDeleteIndexs[j2]].id);
                                }
                                addStyle(UserCode, CustomerCode, Marks).then(function (isSuccess) {
                                    if (isSuccess) {
                                        //u9.alert("添加标签成功");
                                    }
                                    deleteStyle(UserCode, CustomerCode, Markss).then(function (isSuccess) {
                                        if (isSuccess) {
                                            //u9.alert("删除标签成功");
                                            //u9.alert("修改标签订阅成功");
                                        }
                                        u9.hideLoading();
                                        deferred.resolve(isSuccess);
                                    });
                                });
                            }
                            //每个用户增加标签
                            if (oneAddIndexs.length != 0 && oneDeleteIndexs.length == 0) {
                                for (var i in oneAddIndexs) {
                                    Marks.push(oneStyles[oneAddIndexs[i]].id);
                                }
                                addStyle(UserCode, CustomerCode, Marks).then(function (isSuccess) {
                                    if (isSuccess) {
                                        //u9.alert("修改标签订阅成功");
                                    }
                                    deferred.resolve(isSuccess);
                                    u9.hideLoading();
                                });
                            }
                            //每个用户删除标签
                            if (oneDeleteIndexs.length != 0 && oneAddIndexs.length == 0) {
                                for (var i2 in oneDeleteIndexs) {
                                    Marks.push(oneStyles[oneDeleteIndexs[i2]].id);
                                }
                                deleteStyle(UserCode, CustomerCode, Marks).then(function (isSuccess) {
                                    if (isSuccess) {
                                        //u9.alert("修改标签订阅成功");
                                    }
                                    deferred.resolve(isSuccess);
                                    u9.hideLoading();
                                });
                            }
                        }
                        oneAddIndexs = [];
                        oneDeleteIndexs = [];
                        return deferred.promise;
                    }

                    return {
                        getAllStyle: getAllStyle,
                        clientStyle: clientStyle,
                        addStyleToClient: addStyleToClient,
                        changeAllStyleChecked: changeAllStyleChecked,
                        changeStyleChecked: changeStyleChecked,
                        updateAllStyles: updateAllStyles,
                        updateOneStyles: updateOneStyles,
                        deleteClientStyles: deleteClientStyles,
                        deleteOneClientStyles:deleteOneClientStyles
                    }
                })

                .controller('StatesCtrl', function ($scope, $state, $rootScope, Clients,Styles) {
                    u9.hideLoading();
                    $scope.selectedClients = [];
                    Clients.allSelectedClients().then(function (clients) {

                        if(clients && clients.length>0){
                            Clients.getClientsMsgCount(clients).then(function (data) {
                                $scope.selectedClients = data;
                            });
                        }
                    });
                    $scope.addClient = function () {
                        $state.go('clients', {});
                    }

                    $scope.getStyles = function () {
                        $state.go('styles', {});
                    }

                    $scope.showDetail = function (id) {

                        $state.go('clientdetail', {
                            clientId: id
                        });
                    }
                    $scope.changeClientStyle = function (id) {
                        $state.go('styles', {
                            clientId: id
                        });
                    }
                    $scope.deleteClientStyle = function (selectedClient) {
                        Styles.deleteOneClientStyles(selectedClient).then(function (data) {
                            Clients.deleteClientStyle(selectedClient.id);
                        });
                    }
                })

                .controller('MessageDetailCtrl', function ($scope, $state, $rootScope, Clients, $stateParams, Messages) {
                    var html_canvas;
                    $scope.messageId = $stateParams.messageId;
                    console.log($scope.messageId);
                    var messages = Messages.all();
                    for(var i in messages) {
                        if(messages[i].id == $scope.messageId) {
                            $scope.messageDetail = messages[i];
                        }
                    }
                    //Messages.getMessageDetail($scope.messageId).then(function (data) {
                    //
                    //});
                    var cutContent = document.getElementById('cutContent');
                    html2canvas(cutContent, {
                        onrendered: function (canvas) {

                            html_canvas = canvas.toDataURL();
                            //c.toDataURL("image/png")
                        }
                    });
                    $scope.share = function () {
                        parent.window.plugins.socialsharing.share('分享', null, html_canvas, null);
                    }

                })
                .controller('PushMessageDetailCtrl', function ($scope, $state, $rootScope, Clients, $stateParams, Messages) {
                    var html_canvas;
                    $scope.messageId = $stateParams.messageId;
                    console.log($scope.messageId);
                    Messages.getClientCode($scope.messageId).then(function (data) {
                        Messages.getUnreadData(data.Code, data.name).then(function (data) {
                            $scope.msgList = data;
                            for(var i in $scope.msgList) {
                                if($scope.msgList[i].id == $scope.messageId) {
                                    $scope.messageDetail = $scope.msgList[i];
                                }
                            }
                        });
                    });
                    var cutContent = document.getElementById('cutContent');
                    html2canvas(cutContent, {
                        onrendered: function (canvas) {
                            html_canvas = canvas.toDataURL();
                        }
                    });
                    $scope.share = function () {
                        parent.window.plugins.socialsharing.share('分享', null, html_canvas, null);
                    }
                })

                .controller('ClientsCtrl', function ($scope, $ionicScrollDelegate, filterFilter, Clients, $state, Styles) {
                    $scope.searchClient = '';
                    //联系人信息数组
                    $scope.contacts = [];
                    //字母数组
                    $scope.quickCambers = [];
                    //选中的字母
                    $scope.activeCamber = '';
                    function initQuickBar() {
                        if ($scope.contacts.length > 0) {
                            for (var i = 65; i < 91; i++) {
                                $scope.quickCambers.push(String.fromCharCode(i));
                            }
                            for (var i = 0; i < $scope.contacts.length; i++) {
                                var letter = $scope.contacts[i].letter;
                                var isLetter = $scope.contacts[i].isLetter;
                                if (letter != undefined && letter.charCodeAt(0) >= 65 && letter.charCodeAt(0) < 91 && isLetter == true) {
                                    $scope.activeCamber = letter;
                                    break;
                                }
                            }
                        } else {
                            $scope.quickCambers = [];
                            $scope.activeCamber = '';
                        }
                    }

                    // 初始化数据
                    function initData() {
                        Clients.getClientsDatas().then(function (contacts) {
                            $scope.contacts = contacts;
                            initQuickBar();
                        });
                    }

                    initData();
                    $scope.getItemHeight = function (item) {
                        var height = 0;
                        var isLetter = item.isLetter;
                        if (isLetter == undefined) {
                            height = 60;
                        }
                        else {
                            height = 30;
                        }
                        return height;
                    };
                    $scope.scrollBottom = function () {
                        $ionicScrollDelegate.scrollBottom(true);
                    };
                    $scope.clearSearch = function () {
                        $scope.searchClient = '';
                    };
                    $scope.returnStates = function () {
                        $state.go('states', {});
                    };
                    var temp = Clients.allSelected();
                    // 选中处理
                    if (temp == null) {
                        $scope.selected = [];
                    }
                    else {
                        $scope.selected = temp;
                    }
                    var updateSelected = function (action, id) {

                        if (action === 'add' && $scope.selected.indexOf(id) === -1) {
                            $scope.selected.push(id);
                        }
                        if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
                            $scope.selected.splice($scope.selected.indexOf(id), 1);
                        }
                    };
                    $scope.updateSelection = function ($event, id) {
                        var checkbox = $event.target;
                        //add(选中的添加到删除列表），remove(未选中的移除删除列表))
                        var action = (checkbox.checked ? 'add' : 'remove');
                        updateSelected(action, id);

                    };
                    //设置选中状态
                    $scope.isSelected = function (id) {
                        return $scope.selected.indexOf(id) >= 0;
                    };
                    //确定取消标签订阅
                    $scope.confirmSelected = function () {
                        Clients.addSelectedClients($scope.selected).then(function (deletes) {
                            if (deletes && deletes.length > 0) {
                                Styles.deleteClientStyles(deletes).then(function (isSuccess) {
                                    $state.go('states', {});
                                });
                            }
                            $state.go('states', {});
                        });
                    };
                })

                .controller('StylesCtrl', function ($scope, $state, Styles, Clients, $stateParams) {
                    $scope.clientId = $stateParams.clientId;
                    //所有客户的style获取(本地或网络 获取)
                    if ($scope.clientId == null || $scope.clientId == "") {
                        Styles.getAllStyle().then(function (styles) {
                            $scope.styles = styles;
                            //把所有的style加入到每个客户数据中，设置true、false
                            Styles.addStyleToClient();
                        });
                    }
                    else//单个客户的style获取
                    {
                        $scope.styles = Styles.clientStyle($scope.clientId);
                    }
                    //点击标签，记录选中状态
                    $scope.myselect = function (_index) {
                        if ($scope.clientId == null || $scope.clientId == "") {
                            $scope.styles = Styles.changeAllStyleChecked(_index);
                        }
                        else {
                            $scope.styles = Styles.changeStyleChecked($scope.clientId, _index)
                        }
                    }
                    //确认客户订阅的标签，上传到网络
                    $scope.confirmSelected = function () {
                        if ($scope.clientId == null || $scope.clientId == "") {
                            Styles.updateAllStyles().then(function (isSuccess) {
                                if (isSuccess) {
                                    console.log(isSuccess);
                                }
                                $state.go('states', {});
                            });
                        }
                        else {
                            Styles.updateOneStyles($scope.clientId).then(function (isSuccess) {
                                if (isSuccess) {
                                    console.log(isSuccess);
                                }
                                $state.go('states', {});
                            });
                        }
                    }
                })
                .controller('ClientDetailCtrl', function ($scope, $state, $stateParams, Clients, Messages, States,shareCombobox) {
                    //客户信息
                    $scope.client = Clients.getClient($stateParams.clientId);
                    //消息列表
                    $scope.msgList = [];
                    $scope.msgSearch = "";
                    var lineChart;//线状图
                    var month = 0;//存查看图表数据的起始月份
                    //整年数据
                    var data1 = [],data2 = [];
                    //前五个月数据
                    var data1_5 = [],data2_5 = [];
                    //$scope.loadMore = function () {
                    //    $scope.msgList = Messages.loadMoreData();
                    //    $scope.$broadcast('scroll.infiniteScrollComplete');
                    //};

                    $scope.toMessageDetail = function (id) {
                        Messages.setMsgRead(id);
                        $state.go('messagedetail', {
                            messageId: id ,
                            clientCode:$scope.client.Code
                        });
                    };

                    $scope.doRefresh = function () {
                        if ($scope.btn.checked) {

                        }
                        if (!$scope.btn.checked) {
                            //$scope.msgList = Messages.getUpdateData();
                            Messages.getUnreadData($scope.client.Code, $scope.client.name).then(function (data) {
                                $scope.msgList = data;
                            });
                        }
                        $scope.$broadcast('scroll.refreshComplete');
                    };
                    //初始化，消息按钮按下，显示消息
                    $scope.initButtonActive = function () {

                        $scope.btn = {
                            checked: false,
                            defaultbtnleft: 'btn-left-active',
                            defaultbtnright: 'btn-right-active'
                        }
                    };

                    $scope.changeActive = function (type) {

                        if (type == 0) {
                            $scope.btn = {
                                checked: true,
                                defaultbtnleft: 'btn-left',
                                defaultbtnright: 'btn-right'
                            };
                            States.getClientState($stateParams.clientId).then(function (data) {
                                //财务信息
                                $scope.financelist = data[0].finance_msg.detail;
                                //业务信息
                                $scope.businesslist = data[0].business_msg.detail;
                            });
                        }
                        else if (type == 1) {
                            $scope.btn = {
                                checked: false,
                                defaultbtnleft: 'btn-left-active',
                                defaultbtnright: 'btn-right-active'
                            };
                        }
                    };
                    $scope.toggleGroup = function (group) {
                        if ($scope.isGroupShown(group)) {
                            $scope.shownGroup = null;
                        } else {
                            $scope.shownGroup = group;
                        }
                        $scope.IsBottom = false;
                    };
                    $scope.isGroupShown = function (group) {
                        return $scope.shownGroup === group;
                    };

                    $scope.toggleGroup2 = function (group) {
                        if ($scope.isGroupShown2(group)) {
                            $scope.shownGroup2 = null;
                        } else {
                            $scope.shownGroup2 = group;
                        }
                        $scope.IsBottom = false;
                    };
                    $scope.isGroupShown2 = function (group) {
                        return $scope.shownGroup2 === group;
                    };
                    $scope.toggleGroup3 = function (group) {
                        if ($scope.isGroupShown3(group)) {
                            $scope.shownGroup3 = null;
                        } else {
                            $scope.shownGroup3 = group;
                            States.getClientStateChart($stateParams.clientId).then(function (data) {
                                //去年今年数据都初始化为0
                                data1 = [];
                                data2 = [];
                                for(var j = 0;j < 12;j++) {
                                    data1.push({
                                        Money: 0, Month: j+1
                                    });
                                    data2.push({
                                        Money: 0, Month: j+1
                                    });
                                }
                                //加上有数据的月份
                                for(var a in data[1].MonthMoneylist){
                                    data1[parseInt(data[1].MonthMoneylist[a].Month,10)-1].Money = data[1].MonthMoneylist[a].Money/10000;
                                }
                                for(var b in data[0].MonthMoneylist){
                                    data2[parseInt(data[0].MonthMoneylist[b].Month,10)-1].Money = data[0].MonthMoneylist[b].Money/10000;
                                }
                                initCharts(data1,data2);
                            });
                        }
                        $scope.IsBottom = false;

                    };
                    $scope.isGroupShown3 = function (group) {
                        return $scope.shownGroup3 === group;
                    };
                    $scope.initData = function () {
                        $scope.initButtonActive();
                        $scope.doRefresh();
                    };

                    $scope.initData();

                    function initCharts(data1,data2) {
                        var phoneWith = window.innerWidth;
                        var phoneHeight = window.innerHeight;
                        var linedom = document.getElementById('lineDom');
                        linedom.style.width = phoneWith * 0.95 + 'px';
                        linedom.style.height = (phoneHeight) * 0.5 + 'px';
                        lineChart = echarts.init(linedom);
                        var lineSetOption = {
                            title: {
                                text: '订货金额趋势图',
                                x: 'left',
                                textStyle: {
                                    fontWeight: 'normal',
                                    fontSize: 16
                                }
                            },
                            tooltip: {
                                trigger: 'axis',
                                formatter: function (params) {

                                    return  params[0].name +'订货金额'+ '<br/>'
                                        +params[0].seriesName + params[0].value + '万<br/>'
                                        +params[1].seriesName + params[1].value + '万<br/>'
                                },
                                backgroundColor: 'rgba(255,255,255,0.7)',
                                borderColor: '#DCDCDC',
                                borderWidth: '2',
                                textStyle: {color: '#666666'}
                            },
                            legend: {
                                data: ['去年', '今年'],
                                x: 180,
                                y: 45,
                                selectedMode: false,
                                //textStyle: {
                                //    color: '#778899'
                                //}
                                itemHeight:10
                            },
                            grid: {
                                top:80,
                                borderWidth: 0
                            },
                            calculable: false,
                            animation: true,
                            addDataAnimation: false,
                            xAxis: [
                                {
                                    type: 'category',
                                    //nameTextStyle: {
                                    //    color: '#778899'
                                    //},
                                    data: (function () {
                                        var res = [];
                                        var len = data1.length;
                                        while (len--) {
                                            res.unshift(data1[len].Month + '月');
                                        }
                                        return res;
                                    })(),
                                    boundaryGap: false,
                                    splitLine: {
                                        show: false
                                    },
                                    axisTick: {
                                        show: false
                                    }
                                }
                            ],
                            yAxis: [
                                {
                                    type: 'value',
                                    name: '单位：万元',
                                    //nameTextStyle: {
                                    //    color: '#778899'
                                    //},
                                    splitArea: {
                                        show: true,
                                        areaStyle: {
                                            color: ['rgba(255,255,255,0)', 'rgba(255,255,255,0)']
                                        }
                                    },
                                    axisLine: {
                                        show: true,
                                        lineStyle: {
                                            width: 0.1
                                        }
                                    },
                                    axisTick: {
                                        show: false
                                    }
                                }
                            ],
                            dataZoom: {
                                type: 'inside',
                                start: 0,
                                end: 40
                            },
                            series: [
                                {
                                    name: '去年',
                                    type: 'line',
                                    symbol: 'circle',
                                    symbolSize: 6,
                                    itemStyle: {
                                        normal: {
                                            color: '#BEBEBE'
                                        },
                                        emphasis: {
                                            color: '#778899'
                                        }
                                    },
                                    data: (function () {
                                        var res = [];
                                        for(var i in data1){
                                            res[i] = data1[i].Money;
                                        }
                                        return res;
                                    })()
                                },
                                {
                                    name: '今年',
                                    type: 'line',
                                    symbol: 'circle',
                                    symbolSize: 6,
                                    itemStyle: {
                                        normal: {
                                            color: 'rgba(53,204,249,1)'
                                        },
                                        emphasis: {
                                            color: '#00868B'
                                        }
                                    },
                                    data: (function () {
                                        var res = [];
                                        for(var i in data2){
                                            res[i] = data2[i].Money;
                                        }
                                        return res;
                                    })()
                                }
                            ]
                        };
                        lineChart.clear();
                        lineChart.setOption(lineSetOption);
                    }
                    $scope.shareChartImage = function () {
                                var option = {type: 'png',
                                    pixelRatio:1,
                                    backgroundColor:"#fff"
                                };


                                var u = navigator.userAgent;
                                if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {//安卓手机
                                    parent.window.plugins.socialsharing.share('分享', null, lineChart.getDataURL(option), null);
                                } else if (u.indexOf('iPhone') > -1) {//苹果手机
                                    shareCombobox.show({
                                        buttonClicked: function (index) {
                                            shareWeChat(lineChart.getDataURL(option), index, function () {
                                                //alert("分享成功");
                                            }, function (reason) {
                                                //alert(reason);
                                            });
                                            return true;
                                        }
                                    });
                                }


                    };
                    function shareWeChat(uri, index, successCallback, failCallback) {
                        parent.window.Wechat.setOptions({
                            appId: 'wx75e363993c0f2683'
                        });
                        var params = {
                            "scene": 1,
                            "message": {
                                "title": "[TEST]send-photo",
                                "description": "[TEST]Sending from test application",
                                "thumb": uri,
                                "mediaTagName": "TEST-TAG-001",
                                "messageExt": "这是第三方带的测试字段",
                                "messageAction": "<action>dotalist</action>",
                                "media": {
                                    type: 4,
                                    image: uri
                                }
                            }
                        };
                        params.scene = index;
                        parent.window.Wechat.share(params, function () {
                            successCallback();
                        }, function (reason) {
                            if (reason == '参数错误') {
                                u9.alert('图片太大，微信接口限制大小，请截屏分享！');
                            }
                            failCallback(reason)
                        });

                    }
                })
            angular.element(document).ready(function () {
                angular.bootstrap(document, ['myApp']);
            });
        });
});